package com.itheima.springbootsecurity.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
@Data
public class JWTUtils {

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Integer expiration;
    @Value("${jwt.token-http-header}")
    private String tokenHttpHeader;
    @Value("${jwt.token-redis-key-prefix}")
    private String tokenRedisKeyPrefix;

    /**
     * 创建Token
     * @param claims token中包含的数据
     * @return token字符串
     */
    public String createToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claim", claims)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + expiration * 1000))
                .sign(Algorithm.HMAC256(secret));
    }

    /**
     * 校验Token
     * @param token 被校验的token
     * @return token中包含的数据
     */
    public Map<String, Object>verifyToken(String token) {
        return JWT.require(Algorithm.HMAC256(secret))
                .build()
                .verify(token)
                .getClaim("claim")
                .asMap();
    }
}
